package net.ftzcode.service

import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.LoadingCache
import net.ftzcode.dao.UserRepository
import net.ftzcode.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
import javax.annotation.PostConstruct


/**
 * Created by MAC on 2017/5/7.
 */

@Service
open class UserService {

    @Autowired
    private lateinit var userRepository: UserRepository

    private var loadingCache: LoadingCache<String, User>? = null


    @PostConstruct
    fun init() {
        val cache = Caffeine.newBuilder()
        loadingCache = cache.maximumSize(300).expireAfterWrite(10, TimeUnit.MINUTES)
                .expireAfterAccess(10, TimeUnit.MINUTES).build({ key -> getUserByToken(key) })
    }

    fun findUserByCache(token: String): User? {
        return loadingCache!!.get(token)
    }

    fun save(user: User): User {
        return userRepository.save(user)
    }

    fun get(id: Int): User {

        return userRepository.getOne(id)
    }

    private fun getUserByToken(token: String): User {
        return userRepository.findTop1ByToken(token)
    }


}